<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>学生列表</title>
    <link th:href="@{/css/bootstrap.min.css?v=3.3.7}" rel="stylesheet"/>
    <link rel="stylesheet" th:href="@{/css/plugins/layui/css/layui.css}">
    <style>
        body {
            padding: 10px;
        }

        .layui-form-item .layui-inline {
            margin: 10px 0px;
            padding-left: 15px;
        }

        #condition, #tableDiv {
            background: #fff;
        }
    </style>
</head>
<body>

<form id="condition">
    <div class="layui-form-item">
        <div class="layui-inline">
            <div class="layui-input-inline layui-input-wrap">
                <input type="text" placeholder="请输入姓名" id="name" name="name" class="layui-input">
            </div>
            <div class="layui-input-inline layui-input-wrap">
                <input type="text" placeholder="请输入地址" id="address" name="address" class="layui-input">
            </div>
            <button type="button" id="search" class="layui-btn">查询</button>
            <button type="reset" id="reset" class="layui-btn">重置</button>
        </div>
    </div>
</form>

<div style="padding: 16px;">
    <table class="layui-hide" id="test" lay-filter="test"></table>
</div>

<script type="text/html" id="toolbarDemo">
    <button class="layui-btn layui-btn-sm" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i> 新增
    </button>
    <button class="layui-btn layui-btn-sm" lay-event="update">
        <i class="layui-icon layui-icon-edit"></i> 编辑
    </button>
    <button class="layui-btn layui-btn-sm" lay-event="del">
        <i class="layui-icon layui-icon-delete"></i> 删除
    </button>
    <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
    <button class="layui-btn layui-btn-sm" lay-event="getData">获取当前页数据</button>
</script>

<script type="text/html" id="toolDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs" lay-event="more">
            更多
            <i class="layui-icon layui-icon-down"></i>
        </a>
    </div>
</script>

<script th:src="@{/js/plugins/layui/layui.js}"></script>
<script>
    layui.use(['table', 'layer', 'dropdown'], function () {
        var $ = layui.$;
        var table = layui.table;
        var layer = layui.layer;
        var dropdown = layui.dropdown;

        // 创建渲染实例
        table.render({
            elem: '#test',
            url: '/student/list', // 此处为静态模拟数据，实际使用时需换成真实接口
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips',
                onClick: function (obj) { // 2.9.12+
                    layer.alert('自定义工具栏图标按钮');
                }
            }],
            css: [ // 重设当前表格样式
                '.layui-table-tool-temp{padding-right: 145px;}'
            ].join(''),
            cellMinWidth: 80,
            totalRow: true, // 开启合计行
            page: true,
            cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'sid', fixed: 'left', width: 80, title: 'ID', sort: true, totalRow: '合计：'},
                    {field: 'studentNum', title: '学号'},
                    {field: 'studentName', title: '学生姓名'},
                    {field: 'gender', title: '性别', templet: function (d) {
                            if (d.gender === 0) {
                                return '男';
                            } else if (d.gender === 1) {
                                return '女';
                            } else if (d.gender === 2) {
                                return '保密';
                            }
                        }},
                    {field: 'age', title: '年龄'},
                    {field: 'birthday', title: '出生日期', sort: true},
                    {field: 'classId', title: '班级编号'},
                    {field: 'hotelId', title: '宿舍编号'},
                    {field: 'phone', title: '联系电话'},
                    {field: 'email', title: '电子邮件地址'},
                    {field: 'homeAddress', title: '家庭住址'},
                    {field: 'emergencyContact', title: '紧急联系人姓名'},
                    {field: 'emergencyContactPhone', title: '紧急联系人联系电话'},
                    {field: 'major', title: '专业', templet: function (m) {
                            if (m.major === undefined) {
                                return '暂无专业';
                            } else {
                                return m.major.major;
                            }
                        }},
                    {field: 'status', title: '学生状态', templet: function (d) {
                            if (d.status === 0) {
                                return '在读';
                            } else if (d.status === 1) {
                                return '毕业';
                            }
                        }},
                    {field: 'delFlag', title: '删除标志', templet: function (d) {
                            if (d.delFlag === 0) {
                                return '存在';
                            } else if (d.delFlag === 1) {
                                return '删除';
                            }
                        }},
                    {field: 'createBy', title: '创建者'},
                    {field: 'createTime', title: '创建时间', sort: true},
                    {field: 'updateBy', title: '更新者'},
                    {field: 'updateTime', title: '更新时间', sort: true},
                    {field: 'remark', title: '备注'},
                    {field: 'address', title: '地址'},
                    {fixed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#toolDemo'}
                ]
            ],
            error: function (res, msg) {
                console.log(res, msg);
            }
        });

        // 工具栏事件
        table.on('toolbar(test)', function (obj) {
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = $(this);
            switch (obj.event) {
                case 'add':
                    layer.open({
                        title: '添加学生',
                        type: 2,
                        area: ['70%', '80%'],
                        content: '/student/toadd',
                        fixed: false, // 不固定
                        maxmin: true,
                        shadeClose: true,
                        btn: ['立即提交', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            // 获取 iframe 的窗口对象
                            var iframeWin = window[layero.find('iframe')[0]['name']];
                            let studentNum = iframeWin.$('#studentNum').val(); // 获取学号
                            let name = iframeWin.$('#studentName').val();
                            let birthday = iframeWin.$('#birthday').val();
                            let gender = iframeWin.$('input[name="gender"]:checked').val();
                            let age = iframeWin.$('#age').val();
                            let classId = iframeWin.$('#classId').val();
                            let hotelId = iframeWin.$('#hotelId').val();
                            let phone = iframeWin.$('#phone').val();
                            let email = iframeWin.$('#email').val();
                            let homeAddress = iframeWin.$('#homeAddress').val();
                            let emergencyContact = iframeWin.$('#emergencyContact').val();
                            let emergencyContactPhone = iframeWin.$('#emergencyContactPhone').val();
                            let major = iframeWin.$('#major').val();
                            let status = iframeWin.$('input[name="status"]:checked').val();
                            let remark = iframeWin.$('#remark').val();

                            // 验证字段
                            if ($.trim(studentNum) === '') {
                                layer.msg('学号不能为空');
                                return;
                            }
                            if ($.trim(name) === '') {
                                layer.msg('姓名不能为空');
                                return;
                            }
                            if ($.trim(birthday) === '') {
                                layer.msg('出生日期不能为空');
                                return;
                            }
                            if (!gender) {
                                layer.msg('性别不能为空');
                                return;
                            }

                            // 提交表单数据
                            $.ajax({
                                url: '/student/add',
                                type: 'post',
                                data: {
                                    studentNum: studentNum,
                                    studentName: name,
                                    birthday: birthday,
                                    gender: gender,
                                    age: age,
                                    classId: classId,
                                    hotelId: hotelId,
                                    phone: phone,
                                    email: email,
                                    homeAddress: homeAddress,
                                    emergencyContact: emergencyContact,
                                    emergencyContactPhone: emergencyContactPhone,
                                    major: major,
                                    status: status,
                                    remark: remark
                                },
                                dataType: 'json',
                                success: function (res) {
                                    if (res.code === 0) {
                                        layer.msg('添加成功', {icon: 1});
                                        layer.close(index); // 关闭弹窗
                                        table.reload('test'); // 重新加载表格数据
                                    } else {
                                        layer.msg(res.msg, {icon: 2});
                                    }
                                },
                                error: function () {
                                    layer.msg('系统错误', {icon: 2});
                                }
                            });
                        },
                        btn2: function (index, layero) {
                            layer.close(index); // 关闭弹窗
                        }
                    });
                    break;

                case 'update':
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择一行数据进行编辑', {icon: 3});
                        return false;
                    }
                    if (data.length > 1) {
                        layer.msg('只能选择一行数据进行编辑', {icon: 3});
                        return false;
                    }
                    layer.open({
                        title: '编辑学生',
                        type: 2,
                        area: ['70%', '80%'],
                        content: '/student/toupdate/' + data[0].sid,
                        fixed: false, // 不固定
                        maxmin: true,
                        shadeClose: true,
                        btn: ['立即提交', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            // 获取 iframe 的窗口对象
                            var iframeWin = window[layero.find('iframe')[0]['name']];
                            let studentNum = iframeWin.$('#studentNum').val(); // 获取学号
                            let name = iframeWin.$('#studentName').val();
                            let birthday = iframeWin.$('#birthday').val();
                            let gender = iframeWin.$('#gender').val();
                            let age = iframeWin.$('#age').val();
                            let classId = iframeWin.$('#classId').val();
                            let hotelId = iframeWin.$('#hotelId').val();
                            let phone = iframeWin.$('#phone').val();
                            let email = iframeWin.$('#email').val();
                            let homeAddress = iframeWin.$('#homeAddress').val();
                            let emergencyContact = iframeWin.$('#emergencyContact').val();
                            let emergencyContactPhone = iframeWin.$('#emergencyContactPhone').val();
                            let major = iframeWin.$('#major').val();
                            let status = iframeWin.$('input[name="status"]:checked').val();
                            let remark = iframeWin.$('#remark').val();


                            $.ajax({
                                url: '/student/updateSave',
                                type: 'post',
                                data: {
                                    sid: data[0].sid,
                                    studentNum: studentNum,
                                    studentName: name,
                                    birthday: birthday,
                                    gender: gender,
                                    age: age,
                                    classId: classId,
                                    hotelId: hotelId,
                                    phone: phone,
                                    email: email,
                                    homeAddress: homeAddress,
                                    emergencyContact: emergencyContact,
                                    emergencyContactPhone: emergencyContactPhone,
                                    major: major,
                                    status: status,
                                    remark: remark
                                },
                                dataType: 'json',
                                success: function (res) {
                                    if (res.code === 0) {
                                        layer.msg('编辑成功', {icon: 1});
                                        layer.close(index); // 关闭弹窗
                                        table.reload('test'); // 重新加载表格数据
                                    } else {
                                        layer.msg(res.msg, {icon: 2});
                                    }
                                },
                                error: function () {
                                    layer.msg('系统错误', {icon: 2});
                                }
                            });
                        },
                        btn2: function (index, layero) {
                            layer.close(index); // 关闭弹窗
                        }
                    });
                    break;
                case 'del':
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择一行数据进行删除', {icon: 3});
                        return false;
                    }
                    layer.confirm('确定删除选中的数据吗？', {icon: 3, title: '提示'}, function (index) {
                        var ids = [];
                        for (var i = 0; i < data.length; i++) {
                            ids.push(data[i].sid);
                        }
                        $.ajax({
                            url: '/student/remove',
                            type: 'post',
                            data: {
                                ids: ids.join(',')
                            },
                            dataType: 'json',
                            success: function (res) {
                                if (res.code === 0) {
                                    layer.msg('删除成功', {icon: 1});
                                    table.reload('test'); // 重新加载表格数据
                                } else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            },
                            error: function () {
                                layer.msg('系统错误', {icon: 2});
                            }
                        });
                        layer.close(index); // 关闭弹窗
                    });
                    break;
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getData':
                    var data = table.cache[id];
                    layer.alert(JSON.stringify(data));
                    break;
            }
        });

        // 行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                layer.open({
                    title: '编辑学生',
                    type: 2,
                    area: ['70%', '80%'],
                    content: '/student/toupdate/' + data.sid,
                    fixed: false, // 不固定
                    maxmin: true,
                    shadeClose: true,
                    btn: ['立即提交', '取消'],
                    btnAlign: 'c',
                    yes: function (index, layero) {
                        // 获取 iframe 的窗口对象
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        let studentNum = iframeWin.$('#studentNum').val(); // 获取学号
                        let name = iframeWin.$('#studentName').val();
                        let birthday = iframeWin.$('#birthday').val();
                        let gender = iframeWin.$('#gender').val();
                        let age = iframeWin.$('#age').val();
                        let classId = iframeWin.$('#classId').val();
                        let hotelId = iframeWin.$('#hotelId').val();
                        let phone = iframeWin.$('#phone').val();
                        let email = iframeWin.$('#email').val();
                        let homeAddress = iframeWin.$('#homeAddress').val();
                        let emergencyContact = iframeWin.$('#emergencyContact').val();
                        let emergencyContactPhone = iframeWin.$('#emergencyContactPhone').val();
                        let major = iframeWin.$('#major').val();
                        let status = iframeWin.$('input[name="status"]:checked').val();
                        let remark = iframeWin.$('#remark').val();


                        if ($.trim(name.val()) === '') {
                            layer.msg('姓名不能为空');
                            return name.focus();
                        }
                        if ($.trim(address.val()) === '') {
                            layer.msg('地址不能为空');
                            return address.focus();
                        }
                        if ($.trim(birthday.val()) === '') {
                            layer.msg('出生日期不能为空');
                            return birthday.focus();
                        }
                        if ($.trim(gender.val()) === '') {
                            layer.msg('性别不能为空');
                            return gender.focus();
                        }

                        $.ajax({
                            url: '/student/updateSave',
                            type: 'post',
                            data: {
                                sid: data[0].sid,
                                studentNum: studentNum,
                                studentName: name,
                                birthday: birthday,
                                gender: gender,
                                age: age,
                                classId: classId,
                                hotelId: hotelId,
                                phone: phone,
                                email: email,
                                homeAddress: homeAddress,
                                emergencyContact: emergencyContact,
                                emergencyContactPhone: emergencyContactPhone,
                                major: major,
                                status: status,
                                remark: remark
                            },
                            dataType: 'json',
                            success: function (res) {
                                if (res.code === 0) {
                                    layer.msg('编辑成功', {icon: 1});
                                    layer.close(index); // 关闭弹窗
                                    table.reload('test'); // 重新加载表格数据
                                } else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            },
                            error: function () {
                                layer.msg('系统错误', {icon: 2});
                            }
                        });
                    },
                    btn2: function (index, layero) {
                        layer.close(index); // 关闭弹窗
                    }
                });
            } else if (obj.event === 'del') {
                layer.confirm('确定删除该条数据吗？', {icon: 3, title: '提示'}, function (index) {
                    $.ajax({
                        url: '/student/remove',
                        type: 'post',
                        data: {
                            ids: data.sid
                        },
                        dataType: 'json',
                        success: function (res) {
                            if (res.code === 0) {
                                layer.msg('删除成功', {icon: 1});
                                obj.del(); // 删除对应行（tr）的DOM结构
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        },
                        error: function () {
                            layer.msg('系统错误', {icon: 2});
                        }
                    });
                    layer.close(index); // 关闭弹窗
                });
            }
        });
    });
</script>
</body>
</html>
